package com.itheima.controller.store;

import com.github.pagehelper.PageInfo;
import com.itheima.controller.BaseServlet;
import com.itheima.domain.store.Question;
import com.itheima.utils.BeanUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/*
反射获取当前访问路径
 */
@WebServlet("/store/question/*")
public class QuestionServlet extends BaseServlet {
    //查询所有
    private void findAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取当前页码和每页显示数
        String pageNum = req.getParameter("pageNum");
        String pageSize = req.getParameter("pageSize");
        //调用业务层查找所有方法
        List<Question> list=questionService.findAll(pageNum,pageSize);
        PageInfo<Question> pageInfo=new PageInfo<Question>(list);
        req.setAttribute("page",pageInfo);
//        将pageinfo重定向到list.jsp页面
        req.getRequestDispatcher("/pages/store/question/list.jsp").forward(req,resp);
    }
    //新增
    private void save(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //获取当前新增对象并封装到question中
        //Map<String, String[]> map = req.getParameterMap();
        //Question question = BeanUtil.fillBean(req, Question.class, "yyyy-MM-dd");

        //1.确认该操作是否支持文件上传操作，enctype="multipart/form-data"
        if(ServletFileUpload.isMultipartContent(req)) {
            //2.创建磁盘工厂对象
            DiskFileItemFactory factory = new DiskFileItemFactory();
            //3.Servlet文件上传核心对象
            ServletFileUpload fileUpload = new ServletFileUpload(factory);
            //4.从request中读取数据
            List<FileItem> fileItems = fileUpload.parseRequest(req);

            //创建一个标记位,标记当前时候有上传文件的操作
            boolean flag = false;
            for(FileItem item :fileItems){
                if(StringUtils.isNotBlank(item.getName())){
                    flag = true;
                    break;
                }
            }

            Question question = BeanUtil.fillBean(fileItems, Question.class);
            //调用业务层新增方法
            String pictureUid = questionService.save(question,flag);
            for (FileItem item : fileItems) {
                //5.当前表单是否是文件表单
                if (!item.isFormField()) {
                    //6.从临时存储文件的地方将内容写入到指定位置
                    item.write(new File(this.getServletContext().getRealPath("download"),pictureUid));
                }
            }

        }

        //新增完成后再次调用servlet查找所有方法
        findAll(req,resp);
    }
    //删除
    private void deleteByIds(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取要删除的ids(是个字符串,可以转成数组)
        String id = req.getParameter("ids");
        System.out.println(id);
        //调用业务层删除方法
        boolean flag=questionService.deleteByIds(id);
        if(flag){
            //删除成功则调用servlet查找所有方法
            findAll(req,resp);
        }else{
            //失败则跳转到错误页面
            req.getRequestDispatcher("/pages/error.jsp").forward(req,resp);
        }
    }
    //编辑第一次点击实际是根据id获取对象,并把id传给编辑框的对象
    private void toUpdate(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //获取当前id
        String id = req.getParameter("id");
        Question question=questionService.findById(id);
//        System.out.println(question);
        req.setAttribute("question",question);
        req.getRequestDispatcher("/pages/store/question/update.jsp").forward(req,resp);
    }

   //编辑
    private void update(HttpServletRequest req, HttpServletResponse resp) throws Exception {

        //1.确认该操作是否支持文件上传操作，enctype="multipart/form-data"
        if(ServletFileUpload.isMultipartContent(req)) {
            //2.创建磁盘工厂对象
            DiskFileItemFactory factory = new DiskFileItemFactory();
            //3.Servlet文件上传核心对象
            ServletFileUpload fileUpload = new ServletFileUpload(factory);
            //4.从request中读取数据
            List<FileItem> fileItems = fileUpload.parseRequest(req);

            //创建一个标记位,标记当前时候有上传文件的操作
            boolean flag = false;
            for(FileItem item :fileItems){
                if(StringUtils.isNotBlank(item.getName())){
                    flag = true;
                    break;
                }
            }

            Question question = BeanUtil.fillBean(fileItems, Question.class);
            //调用业务层新增方法
            questionService.update(question,flag);
            for (FileItem item : fileItems) {
                //5.当前表单是否是文件表单
                if (!item.isFormField()) {
                    //6.从临时存储文件的地方将内容写入到指定位置
                    item.write(new File(this.getServletContext().getRealPath("download"),question.getId()));

                }
            }
        }
        findAll(req,resp);
    }
}
